package com.gzxw.mogublog.commons.config.jwt;

import com.gzxw.mogublog.commons.config.security.LoginUser;
import com.gzxw.mogublog.utils.JsonUtils;
import com.gzxw.mogublog.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class JwtTokenUtil {

    @Value("${audience.base64Secret}")
    private String base64Secret;

    @Value("${tokenHeader}")
    private String tokenHeader;

    @Value("${tokenHead}")
    private String tokenHead;

    @Autowired
    private Audience audience;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser,long expiration) {
        // 刷新token
        refreshToken(loginUser,expiration);
        Map<String, Object> claims = new HashMap<>();
        claims.put("LOGIN_USER_KEY", loginUser.getToken());
        return createToken(claims);
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(base64Secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, base64Secret).compact();
        return token;
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser,long expiration) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expiration);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisUtil.setEx(userKey, JsonUtils.objectToJson(loginUser), audience.getExpiresSecond(), TimeUnit.SECONDS);
    }

    private String getTokenKey(String uuid) {
        return "LOGIN_TOKEN_KEY" + uuid;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String authToken = request.getHeader(tokenHeader);
        try {
            String token = authToken.substring(tokenHead.length());
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get("LOGIN_USER_KEY");
            String userKey = getTokenKey(uuid);
            String user = redisUtil.get(userKey);
            return JsonUtils.jsonToPojo(user, LoginUser.class);
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (currentTime<expireTime) {
            refreshToken(loginUser,audience.getExpiresSecond());
        }
    }


}
